//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.bfsuol.bfsuolcomponents.file.controller;

import com.alibaba.fastjson.JSON;
import com.bfsuol.yihang.file.entity.FileManager;
import com.bfsuol.yihang.file.domain.FileManagerService;
import com.bfsuol.bfsuolframework.core.BfsuolConstants;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.utils.DateTimeUtils;
import com.bfsuol.bfsuolframework.core.utils.FileUtils;
import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping({"/components/fileupload"})
public class FileUploaderController extends SpringControllerSupport {

    @Autowired
    private FileManagerService fileManagerService;

    final Logger log = LoggerFactory.getLogger(FileUploaderController.class);

    public FileUploaderController() {
    }

    @RequestMapping({"/upload"})
    @ResponseBody
    public String upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean uploadSuccess = true;
        String filePath = request.getParameter("path");
        boolean format = StringUtils.parseBoolean(request.getParameter("format"));
        boolean overwrite = StringUtils.parseBoolean(request.getParameter("overwrite"));
        boolean datepath = StringUtils.parseBoolean(request.getParameter("datepath"));
        String uploadPath = FileUtils.getUploadRealPath(new String[]{filePath});
        if(datepath) {
            uploadPath = uploadPath + FileUtils.getDatePath() + "/";
        }

        String fileFullPath = "";
        String fileName = "";

        try {
            FileUtils.createFolder(uploadPath);
        } catch (Exception var27) {
            var27.printStackTrace();
        }

        fileName = request.getHeader("X-File-Name");
        if(fileName != null) {
            fileName = URLDecoder.decode(fileName, "utf-8");
            fileFullPath = this.getFileValidName(uploadPath, fileName, format, overwrite);
            InputStream is = null;
            FileOutputStream fos = null;

            try {
                is = request.getInputStream();
                fos = new FileOutputStream(new File(fileFullPath));
                IOUtils.copy(is, fos);
            } catch (FileNotFoundException var30) {
                uploadSuccess = false;
                if(this.logger.isDebugEnabled()) {
                    var30.printStackTrace();
                }
            } catch (Exception var31) {
                uploadSuccess = false;
                if(this.logger.isDebugEnabled()) {
                    var31.printStackTrace();
                }
            } finally {
                try {
                    fos.close();
                    is.close();
                } catch (IOException var26) {
                    ;
                }

            }
        } else {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(fac);
            upload.setHeaderEncoding("utf-8");
            List fileList = null;

            try {
                fileList = upload.parseRequest(request);
                Iterator it = fileList.iterator();

                while(it.hasNext()) {
                    FileItem item = (FileItem)it.next();
                    if(!item.isFormField()) {
                        fileName = FileUtils.getFileName(item.getName());
                        fileName = URLDecoder.decode(fileName, "utf-8");
                        if(!StringUtils.isBlank(fileName)) {
                            fileFullPath = this.getFileValidName(uploadPath, fileName, format, overwrite);
                            item.write(new File(fileFullPath));
                        }
                    }
                }
            } catch (FileUploadException var28) {
                uploadSuccess = false;
                if(this.logger.isDebugEnabled()) {
                    var28.printStackTrace();
                }
            } catch (Exception var29) {
                uploadSuccess = false;
                if(this.logger.isDebugEnabled()) {
                    var29.printStackTrace();
                }
            }
        }

        FileManager fileManager = new FileManager();
        fileManager.setFilePath(fileFullPath);
        fileManager.setUrl(FileUtils.realPath2Path(fileFullPath));
        fileManager.setFileRealname(FileUtils.getFileName(fileFullPath));
        fileManager.setFileTitle(fileName);
        boolean flag = fileManagerService.save(fileManager);
        //PrintWriter writer = response.getWriter();
        if(uploadSuccess) {
            //response.setStatus(200);
            HashMap map = new HashMap();
            map.put("success",true);
            map.put("fileId",fileManager.getId());
            return JSON.toJSONString(map);
            //writer.print("{\"success\": true,\"fileId\":\"" + fileManager.getId() + "\"}");
        } else {
            //response.setStatus(500);
            HashMap map = new HashMap();
            map.put("success",false);
            return JSON.toJSONString(map);
            //writer.print("{\"success\": false}");
        }

/*        writer.flush();
        writer.close();*/
    }

    @RequestMapping({"/delete/{fileId}"})
    @ResponseBody
    public void delete(@PathVariable("fileId") Long fileId, @RequestParam(defaultValue = "false") Boolean realDelete, HttpServletResponse response) throws Exception {
        boolean deleteSuccess = true;
        Long id = Long.valueOf(0L);
        if(fileId == null) {
            deleteSuccess = false;
        } else {
            FileManager fileManager = (FileManager)this.fileManagerService.getById(fileId);
            if(fileManager != null) {
                id = fileManager.getId();
                if(realDelete.booleanValue()) {
                    FileUtils.deleteFile(fileManager.getFilePath());
                    this.fileManagerService.removeById(fileManager.getId());
                } else {
                    fileManager.setIsDeleted(BfsuolConstants.GLOBAL_YESNO_YES);
                    this.fileManagerService.updateById(fileManager);
                }

                if(realDelete.booleanValue()) {
                    FileUtils.deleteFile(fileManager.getFilePath());
                    this.fileManagerService.removeById(fileManager.getId());
                }
            }
        }

        PrintWriter writer = response.getWriter();
        if(deleteSuccess) {
            response.setStatus(200);
            writer.print("{\"success\": true,\"fileId\":\"" + id + "\"}");
        } else {
            response.setStatus(500);
            writer.print("{\"success\": false}");
        }

        writer.flush();
        writer.close();
    }

    private String getFileValidName(String filePath, String fileName, boolean format, boolean overwrite) {
        String fileValidName;
        if(format) {
            String fileExt = FileUtils.getFileExt(fileName);
            fileValidName = filePath + DateTimeUtils.getCurrentDateTimeString("yyyyMMddHHmmss") + (fileExt == null?"":"." + fileExt);
        } else {
            fileValidName = filePath + fileName;
        }

        if(!overwrite) {
            fileValidName = FileUtils.getValidFileName(fileValidName);
        }

        return fileValidName;
    }
}
